<template>
  <div class="register">
    <el-form ref="registerRef" :model="registerForm" :rules="registerRules" class="register-form">
      <h3 class="title"><img src="@/assets/logo/logo2-02.png" alt="logo" class="logo-img" /></h3>
      <el-form-item v-if="tenantEnabled" prop="tenantId">
        <el-select v-model="registerForm.tenantId" filterable placeholder="请选择/输入公司名称" style="width: 100%">
          <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
          <template #prefix><svg-icon icon-class="company" class="el-input__icon input-icon" /></template>
        </el-select>
      </el-form-item>
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input v-model="registerForm.password" type="password" size="large" auto-complete="off" placeholder="密码" @keyup.enter="handleRegister">
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="确认密码"
          @keyup.enter="handleRegister"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input v-model="registerForm.email" type="text" size="large" auto-complete="off" placeholder="邮箱">
          <template #prefix><svg-icon icon-class="email" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="registerForm.yzm" placeholder="请输入验证码" style="width: 68%">
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <el-button style="display: inline; height: 40px; width: 32%" :disabled="disabled1" @click="fa()">{{ btnText }}</el-button>
      </el-form-item>
      <el-form-item v-if="captchaEnabled" prop="code">
        <el-input v-model="registerForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter="handleRegister">
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="register-code">
          <img :src="codeUrl" class="register-code-img" @click="getCode" />
        </div>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleRegister">
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <div style="float: right">
          <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-register-footer">
      <span>Copyright © 2023-2025 Xunjie Corp All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, register, byEmail, sendSimpleMessage } from '@/api/login';
import { RegisterForm, TenantVO } from '@/api/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { to } from 'await-to-js';

const router = useRouter();

const registerForm = ref<RegisterForm>({
  tenantId: '',
  username: '',
  password: '',
  email: '',
  confirmPassword: '',
  code: '',
  uuid: '',
  userType: 'sys_user',
  yzm: ''
});
const btnText = ref('获取验证码');
const disabled1 = ref(false);

const mailRef = ref({
  to: '',
  subject: ''
});

// 租户开关
const tenantEnabled = ref(false);

const equalToPassword = (rule: any, value: string, callback: any) => {
  if (registerForm.value.password !== value) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const registerRules: ElFormRules = {
  email: [
    // { message: '请输入邮箱', trigger: 'blur' },
    { required: true, type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur'] }
  ],
  tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
  username: [
    { required: true, trigger: 'blur', message: '请输入您的账号' },
    { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入您的密码' },
    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
    { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', message: '请再次输入您的密码' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
};
const codeUrl = ref('');
const loading = ref(false);
const captchaEnabled = ref(false);
const registerRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

const handleRegister = () => {
  registerRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      const [err] = await to(register(registerForm.value));
      console.log(err);
      if (!err) {
        const username = registerForm.value.username;
        await ElMessageBox.alert("<font color='red'>恭喜你，您的账号 " + username + ' 注册成功！</font>', '系统提示', {
          dangerouslyUseHTMLString: true,
          type: 'success'
        });
        await router.push('/login');
      } else {
        loading.value = false;
      }
    }
  });
};

/**发验证码 */
const fa = async () => {
  registerRef.value.validateField('email', async (errorMessage) => {
    // console.log(errorMessage)
    if (!errorMessage) {
      proxy?.$modal.msgError('请输入正确的邮箱');
    } else {
      const res1 = await byEmail(registerForm.value.email, '1');
      if (res1.data == 0) {
        disabled1.value = true;
        btnText.value = '请稍候...';
        mailRef.value.to = registerForm.value.email;
        mailRef.value.subject = '验证码';
        const res = await sendSimpleMessage(mailRef.value);
        if (res.code == 200) {
          proxy?.$modal.msgSuccess(res.msg);
          setTimeout(() => {
            doLoop(60);
          }, 500);
        } else {
          proxy?.$modal.msgError(res.msg);
        }
      }
    }
  });
};
const doLoop = (seconds: any) => {
  seconds = seconds ? seconds : 60;
  btnText.value = seconds + 's后获取';
  let countdown = setInterval(() => {
    if (seconds > 0) {
      btnText.value = seconds + 's后获取';
      --seconds;
    } else {
      btnText.value = '获取验证码';
      disabled1.value = false;
      clearInterval(countdown);
    }
  }, 1000);
};

const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    registerForm.value.uuid = data.uuid;
  }
};

onMounted(() => {});
</script>

<style lang="scss" scoped>
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url('../assets/images/a5c27d1ed21b0ef46dfce1c0cfc451da81cb3e13.png');
  background-size: cover;
}

.title {
  margin: 0 auto 10px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.9);
  width: 420px;
  padding: 40px 40px 20px 40px;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0;
  }
}

.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.register-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #000;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.register-code-img {
  height: 40px;
  padding-left: 12px;
}

.logo-img {
  height: 60px;
  width: 100%;
  max-width: 300px;
  object-fit: contain;
}

/* 添加响应式样式 */
@media screen and (max-width: 768px) {
  .register-form {
    width: 90%;
    margin: 0 auto;
    padding: 30px 20px;
  }

  .el-register-footer {
    font-size: 10px;
  }

  .logo-img {
    max-width: 200px;
  }

  .el-form-item {
    margin-bottom: 15px;
  }
}

@media screen and (max-width: 480px) {
  .register-form {
    width: 95%;
    padding: 20px 15px;
  }

  .logo-img {
    max-width: 150px;
  }

  .el-button {
    padding: 8px 15px;
  }

  .register-code {
    width: 40%;
  }
}
</style>
